import { BaseService } from '@/base/base.service'
import { Injectable } from '@nestjs/common'
import { Role, WxUser } from '@prisma/client'
import { WxUserDto } from './dto/wx-user.dto'
import { PrismaBaseService } from '@/prisma-base/prisma-base.service'
import { LoginWxUserDto } from './dto/login-wx-user.dto'
import { JwtService } from '@nestjs/jwt'
import { RedisService } from '@/redis/redis.service'

@Injectable()
export class WxUserService extends BaseService<WxUser, WxUserDto> {
  constructor(
    private readonly prismaBase: PrismaBaseService,
    private readonly jwt: JwtService,
    private readonly redisService: RedisService,
  ) {
    super('WxUser')
  }

  async wxUserLogin(dto: LoginWxUserDto) {
    const user = await this.prismaBase.wxUser.findUnique({
      where: {
        phone: dto.phone,
      },
    })
    if (!user) {
      const regUser = await this.prismaBase.wxUser.create({
        data: {
          phone: dto.phone,
          nick_name: `用户${Math.floor(1000 + Math.random() * 9000)}`,
        },
      })
      let rUser = this.token(regUser)
      await this.redisService.set(`token@${regUser.id}}`, (await rUser).token, 30 * 24 * 60 * 60)
      return rUser
    } else {
      let lUser = this.token(user)
      await this.redisService.set(`token@${user.id}`, (await lUser).token, 30 * 24 * 60 * 60)
      return lUser
    }
  }

  private async token(user: WxUser) {
    const { phone, id } = user
    return {
      user,
      token: await this.jwt.signAsync({
        phone,
        sub: id,
      }),
    }
  }

  async changeRole(id: string, role: Role) {
    let data
    if (role === 'BROKER') {
      data = {
        role,
        broker_time: new Date(),
      }
    } else {
      data = {
        role,
        broker_time: null,
      }
    }
    await this.prismaBase.wxUser.update({
      where: {
        id,
      },
      data,
    })
    return '修改成功'
  }

  async getUserByPhone(phone: string) {
    return await this.prismaBase.wxUser.findMany({
      where: {
        phone: {
          contains: phone,
        },
      },
    })
  }

  async getNewUser(id: string) {
    return await this.prismaBase.wxUser.findUnique({
      where: {
        id,
      },
      select: {
        id: true,
        avatar: true,
        nick_name: true,
        phone: true,
        role: true,
        createdAt: true,
      },
    })
  }

  async checkToken(token: string, id: string) {
    let redis_token = await this.redisService.get(`token@${id}`)
    if (!redis_token) return false
    if (redis_token === token) {
      return true
    } else {
      return false
    }
  }
}
